<template>
  <div class="app-container">
    <!-- 周历排班视图 -->
    <el-calendar v-loading="loading">
      <template #dateCell="{ date, data }">
        <div
          class="calendar-day"
          @click="showDeptInfo(data)"
        >
          <div class="header">{{ data.day.split('-').slice(1).join('-') }}</div>
          <div class="schedules">
            <div
              v-for="(schedule, index) in getSchedulesByDate(data.day)"
              :key="index"
              class="schedule-item"
            >
              <el-tag size="mini" effect="dark" :type="schedule.deptId % 2? 'primary' :'success'">
                {{ schedule.deptName }}
              </el-tag>
              <span class="doctor-name">{{ schedule.doctName }}</span>
            </div>
            <div v-if="!getSchedulesByDate(data.day).length" class="no-schedule">
              暂无排班
            </div>
          </div>
        </div>
      </template>
    </el-calendar>
    <!-- 科室信息弹出框 -->
    <el-dialog
      title="当日排班科室信息"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div v-if="currentDept">
        <p>科室名称：{{ currentDept.deptName }}</p>
        <p>科室编码：{{ currentDept.deptCode }}</p>
        <p>科室挂号量：{{ currentDept.schedNum }}</p> <!-- 修改为 schedNum -->
        <p>科室负责人：{{ currentDept.deptLeader }}</p>
        <p>科室电话：{{ currentDept.deptPhone }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept } from "@/api/his/dept";
import { listNewschedule, getNewschedule, delNewschedule, addNewschedule, updateNewschedule } from "@/api/his/newschedule";
import { getUserProfile } from "@/api/system/user";

export default {
  name: "ScheduleView",
  data() {
    return {
      loading: true,
      queryParams: {
        week: this.getCurrentMonday(),
        deptId: null,
        startDate: null,
        endDate: null
      },
      scheduleData: {},
      deptOptions: [],
      params: {
        pageNum: 1,
        pageSize: 100,
        doctName: null
      },
      dialogVisible: false, // 控制弹出框的显示和隐藏
      currentDept: null // 当前点击格子对应的科室信息
    };
  },
  created() {
    getUserProfile().then(response => {
      this.params.doctName = response.data.nickName;
    });
    this.initData();
  },
  methods: {
    async initData() {
      try {
        const deptRes = await listDept();
        this.deptOptions = deptRes.rows;
        this.getList();
      } catch (error) {
        console.error("数据加载失败:", error);
      }
    },

    async getList() {
      this.loading = true;
      try {
        const res = await listNewschedule(this.params);
        this.scheduleData = res.rows.reduce((acc, cur) => {
          const date = cur.schedDate;
          if (!acc[date]) acc[date] = [];
          acc[date].push({
           ...cur,
            deptName: this.deptOptions.find(d => d.deptId === cur.deptId)?.deptName || '未知科室'
          });
          return acc;
        }, {});
      } finally {
        this.loading = false;
      }
    },

    // 日期计算方法保持不变
    getCurrentMonday() {
      const today = new Date();
      const day = today.getDay();
      const diff = today.getDate() - day + (day === 0? -6 : 1);
      return new Date(today.setDate(diff)).toISOString().split('T')[0];
    },
    getWeekStartDate() {
      return this.queryParams.week?
        this.formatDate(new Date(this.queryParams.week)) :
        this.formatDate(new Date(this.getCurrentMonday()));
    },
    getWeekEndDate() {
      const start = new Date(this.getWeekStartDate());
      return this.formatDate(new Date(start.setDate(start.getDate() + 6)));
    },
    formatDate(date) {
      return date.toISOString().split('T')[0];
    },

    // 事件处理
    handleWeekChange() {
      this.getList();
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        week: this.getCurrentMonday(),
        deptId: null
      };
      this.getList();
    },

    // 数据获取方法
    getSchedulesByDate(date) {
      return this.scheduleData[date] || [];
    },

    async showDeptInfo(data) {
      const schedule = this.getSchedulesByDate(data.day)[0];
      if (schedule) {
        const deptId = schedule.deptId;
        try {
          const res = await getDept(deptId);
          // 将 schedNum 整合到 currentDept 中
          const { schedNum } = schedule;
          this.currentDept = {
           ...res.data,
            schedNum
          };
          this.dialogVisible = true;
        } catch (error) {
          console.error("获取科室信息失败:", error);
        }
      }
    }
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.app-container {
  padding: 20px;
}

.calendar-day {
  height: 180px;
  padding: 8px;
  overflow: hidden;
}

.header {
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 6px;
  padding-bottom: 2px;
  border-bottom: 1px solid #ebeef5;
}

.schedules {
  height: calc(100% - 24px);
  overflow-y: auto;
}

.schedule-item {
  padding: 6px;
  margin: 4px 0;
  background: #f8faff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.doctor-name {
  margin-left: 8px;
  font-size: 13px;
  color: #606266;
}

.no-schedule {
  color: #909399;
  font-size: 12px;
  text-align: center;
  padding: 10px 0;
}

/* 调整Element组件样式 */
:deep(.el-calendar__header) {
  padding: 12px 20px;
}

:deep(.el-calendar__body) {
  padding: 0;
}

:deep(.el-calendar-table) {
  border-collapse: collapse;

  td {
    border: 1px solid #ebeef5;
    vertical-align: top;
  }

  tr:first-child td {
    border-top: none;
  }
}

:deep(.el-calendar-day) {
  padding: 0!important;
  height: 180px;
}
</style>